<template>
  <view class="edit-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @tap="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">编辑帖子</text>
      <button class="publish-btn" :disabled="!canPublish" @tap="handlePublish">
        发布
      </button>
    </view>

    <!-- 编辑区域 -->
    <scroll-view class="edit-scroll" scroll-y>
      <!-- 图片上传区 -->
      <view class="image-upload">
        <view class="image-list">
          <view 
            class="image-item" 
            v-for="(image, index) in images" 
            :key="index"
          >
            <image :src="image" mode="aspectFill"></image>
            <view class="delete-btn" @tap="deleteImage(index)">
              <uni-icons type="trash" size="20" color="#fff"></uni-icons>
            </view>
          </view>
          <view 
            class="upload-btn" 
            @tap="chooseImage" 
            v-if="images.length < 9"
          >
            <uni-icons type="plusempty" size="32" color="#999"></uni-icons>
            <text>{{ images.length }}/9</text>
          </view>
        </view>
      </view>

      <!-- 文本输入区 -->
      <view class="input-area">
        <input
          class="title-input"
          v-model="title"
          placeholder="添加标题更容易被发现哦~"
          placeholder-class="placeholder"
          maxlength="30"
        />
        <textarea
          class="content-input"
          v-model="content"
          placeholder="分享你的想法..."
          placeholder-class="placeholder"
          maxlength="1000"
          :auto-height="true"
        ></textarea>
      </view>

      <!-- 话题选择 -->
      <view class="topic-select" @tap="showTopicPopup">
        <text class="label"># 添加话题</text>
        <text class="selected-topic" v-if="selectedTopic">{{ selectedTopic.name }}</text>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
    </scroll-view>

    <!-- 话题选择弹窗 -->
    <uni-popup ref="topicPopup" type="bottom">
      <view class="topic-popup">
        <view class="popup-header">
          <text class="title">选择话题</text>
          <view class="close-btn" @tap="hideTopicPopup">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view class="topic-list" scroll-y>
          <view 
            class="topic-item"
            v-for="topic in hotTopics"
            :key="topic.id"
            @tap="selectTopic(topic)"
          >
            <text class="topic-name"># {{ topic.name }}</text>
            <text class="topic-count">{{ topic.postCount }}个内容</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'

export default {
  data() {
    return {
      postId: '',
      title: '',
      content: '',
      images: [],
      selectedTopic: null,
      hotTopics: [],
      isLoading: false
    }
  },

  computed: {
    canPublish() {
      return this.title.trim() && (this.content.trim() || this.images.length > 0)
    }
  },

  onLoad(options) {
    if (options.id) {
      this.postId = options.id
      this.loadPostDetail()
    }
    this.loadHotTopics()
  },

  methods: {
    // 加载帖子详情
    async loadPostDetail() {
      try {
        const { data } = await this.$api.community.post.detail(this.postId)
        this.title = data.title
        this.content = data.content
        this.images = data.images || []
        if (data.topic) {
          this.selectedTopic = {
            id: data.topic.id,
            name: data.topic.name
          }
        }
      } catch (error) {
        console.error('加载帖子详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 加载热门话题
    async loadHotTopics() {
      try {
        const { data } = await this.$api.community.topic.hot()
        this.hotTopics = data
      } catch (error) {
        console.error('加载热门话题失败:', error)
      }
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 9 - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.images = [...this.images, ...res.tempFilePaths]
        }
      })
    },

    // 删除图片
    deleteImage(index) {
      this.images.splice(index, 1)
    },

    // 显示话题选择弹窗
    showTopicPopup() {
      this.$refs.topicPopup.open()
    },

    // 隐藏话题选择弹窗
    hideTopicPopup() {
      this.$refs.topicPopup.close()
    },

    // 选择话题
    selectTopic(topic) {
      this.selectedTopic = topic
      this.hideTopicPopup()
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 发布帖子
    async handlePublish() {
      if (!isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      if (this.isLoading) return
      this.isLoading = true

      try {
        // 上传图片
        const uploadedImages = []
        if (this.images.length > 0) {
          for (const image of this.images) {
            if (image.startsWith('http')) {
              uploadedImages.push(image)
              continue
            }
            const formData = new FormData()
            formData.append('file', image)
            const { data: imageUrl } = await this.$api.post('/api/v1/upload/image', formData)
            uploadedImages.push(imageUrl)
          }
        }

        // 更新帖子
        const postData = {
          title: this.title.trim(),
          content: this.content.trim(),
          images: uploadedImages,
          topicId: this.selectedTopic?.id
        }

        await this.$api.community.post.update(this.postId, postData)

        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })

        // 延迟返回，让用户看到提示
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1500)
      } catch (error) {
        console.error('发布失败:', error)
        uni.showToast({
          title: error.message || '发布失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-container {
  min-height: 100vh;
  background-color: #fff;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  padding-top: var(--status-bar-height);
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;

  .nav-back {
    padding: 20rpx;
    margin-left: -20rpx;
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    color: #333;
    margin: 0 60rpx;
  }

  .publish-btn {
    font-size: 28rpx;
    color: #ff5500;
    background: none;
    padding: 0;
    width: auto;
    margin: 0;

    &:disabled {
      color: #999;
    }
  }
}

.edit-scroll {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  height: calc(100vh - var(--status-bar-height) - 88rpx);
}

.image-upload {
  padding: 30rpx;

  .image-list {
    display: flex;
    flex-wrap: wrap;
    margin: -10rpx;

    .image-item,
    .upload-btn {
      width: calc(33.33% - 20rpx);
      margin: 10rpx;
      position: relative;
      
      &::before {
        content: '';
        display: block;
        padding-top: 100%;
      }
    }

    .image-item {
      image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }

      .delete-btn {
        position: absolute;
        top: -20rpx;
        right: -20rpx;
        width: 40rpx;
        height: 40rpx;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .upload-btn {
      background-color: #f5f5f5;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      text {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }
    }
  }
}

.input-area {
  padding: 0 30rpx;

  .title-input {
    font-size: 32rpx;
    color: #333;
    padding: 20rpx 0;
  }

  .content-input {
    font-size: 28rpx;
    color: #333;
    width: 100%;
    min-height: 200rpx;
  }

  .placeholder {
    color: #999;
  }
}

.topic-select {
  margin: 30rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  align-items: center;

  .label {
    font-size: 28rpx;
    color: #666;
  }

  .selected-topic {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    margin: 0 20rpx;
  }
}

.topic-popup {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  
  .popup-header {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .title {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }

    .close-btn {
      padding: 20rpx;
      margin-right: -20rpx;
    }
  }

  .topic-list {
    max-height: 60vh;
    padding: 0 30rpx;

    .topic-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .topic-name {
        font-size: 28rpx;
        color: #333;
      }

      .topic-count {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}
</style> 